import { computed } from 'vue';
import type { BlogPost, PostDependency, PostMilestone } from '@/components/GanttChart/types';
import type { GSTCAPI } from 'gantt-schedule-timeline-calendar';

export function useGanttData(api: GSTCAPI) {
  // 合并文章和里程碑数据
  const mergedItems = computed(() => {
    const posts = api.state.get('config.list.rows') as BlogPost[];
    const milestones = api.state.get('config.chart.milestones') as PostMilestone[];

    return [
      ...posts.map(post => ({
        ...post,
        type: 'post',
        time: {
          start: new Date(post.startDate),
          end: new Date(post.endDate)
        }
      })),
      ...milestones.map(milestone => ({
        ...milestone,
        type: 'milestone',
        time: {
          start: new Date(milestone.date),
          end: new Date(new Date(milestone.date).getTime() + 24 * 60 * 60 * 1000)
        }
      }))
    ];
  });

  // 获取当前可见范围内的项目
  const visibleItems = computed(() => {
    const visibleTime = api.state.get('config.chart.time.visible');
    return mergedItems.value.filter(
      item => item.time.start <= visibleTime.to && item.time.end >= visibleTime.from
    );
  });

  // 根据ID获取文章
  const getPostById = (id: string) =>
    api.state.get('config.list.rows').find((post: BlogPost) => post.id === id);

  // 获取文章的依赖关系
  const getPostDependencies = (postId: string) => {
    const deps = api.state.get('config.chart.dependencies') as PostDependency[];
    return deps.filter(dep => dep.sourcePost === postId || dep.targetPost === postId);
  };

  // 计算文章进度
  const calculateProgress = (post: BlogPost) => {
    const now = new Date().getTime();
    const start = new Date(post.startDate).getTime();
    const end = new Date(post.endDate).getTime();

    if (now <= start) return 0;
    if (now >= end) return 1;

    return (now - start) / (end - start);
  };

  // 更新文章的自动进度
  const updateAutoProgress = () => {
    const posts = api.state.get('config.list.rows') as BlogPost[];
    const updates = posts
      .filter(post => post.status === 'writing')
      .map(post => ({
        id: post.id,
        progress: calculateProgress(post)
      }));

    if (updates.length > 0) {
      api.updateConfig({
        list: {
          rows: posts.map(post => {
            const update = updates.find(u => u.id === post.id);
            return update
              ? {
                  ...post,
                  progress: update.progress
                }
              : post;
          })
        }
      });
    }
  };

  // 设置自动进度更新定时器
  const setupProgressTimer = () => {
    updateAutoProgress();
    return setInterval(updateAutoProgress, 60 * 60 * 1000); // 每小时更新一次
  };

  return {
    mergedItems,
    visibleItems,
    getPostById,
    getPostDependencies,
    calculateProgress,
    updateAutoProgress,
    setupProgressTimer
  };
}
